package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiSyncDemo* @Description:系统API接口开发Demo ，重点关注业务逻辑部分
 * @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiChatLoginDeal implements ServiceBackInvoke {

    private static final Log log = LogFactory.getLog(apiChatLoginDeal.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        JSONObject result = new JSONObject();

        //获取所有参数名
        JSONObject Params_Json = new JSONObject();
        Enumeration ElementInfo = request.getParameterNames();
        while (ElementInfo.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) ElementInfo.nextElement();
            //再通过的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
            Params_Json.put(parameterName, request.getParameter(parameterName));
        }

        String openid= "";
        String phone_number = "";
        String nickname = "";
        String customer_Guid = "";
        String queue = "";
        String from = "";
        JSONObject loginInfo = new JSONObject();
        String loginName = "";
        String password = "";
        try {
            //业务逻辑部分
            openid = KHUtil.FastJsonNull(request.getParameter("openid")); // 微信与小程序唯一ID
            queue = KHUtil.FastJsonNull(request.getParameter("queue")); // 进线队列

            if(FindString(openid)||FindString(queue)){
                result.put("state", "-1");
                result.put("success", false);
                result.put("msg", "参数传递含非法字符！");
                return result;
            }


            log.debug("【原始Get请求参数】-openid:" + openid );

            if (KHUtil.isNull(openid)) {
                result.put("state", "0");
                result.put("success", false);
                result.put("msg", "OPENID传空-按访客处理");

            } else {
                String dealSQL = "select CUSTOMER_GUID,STRINGFIELD9,STRINGFIELD11 from customer where open_id =? or mini_id=?";
                List<Map<String, Object>> selectExits = jt.queryForList(dealSQL, openid,openid);


                if(selectExits.size()==0) {
                    result.put("state", "0");
                    result.put("success", false);
                    result.put("msg", "未查到OPENID-按访客处理");
                    log.warn("未检索到最终客户信息-继续按匿名访客处理");
                }else{
                    customer_Guid = selectExits[0].getAt("CUSTOMER_GUID");
                    loginInfo.put("loginName", selectExits[0].getAt("STRINGFIELD9"));
                    loginInfo.put("password", selectExits[0].getAt("STRINGFIELD11"));
                    // 处理返回数据
                    result.put("state", "1");
                    result.put("success", true);
                    result.put("msg", "接口调用成功");
                    result.put("result", loginInfo);
                };

            }

        } catch (Exception e) {
            log.error("接口调用异常！", e);
            result.put("state", "0");
            result.put("success", false);
            result.put("msg", "接口调用失败");
            JSONObject rresult = new JSONObject();
            result.put("result", rresult);
        }



        return result;
    }




    public static boolean FindString(String input) {
        // 正则表达式的字符串，注意特殊字符需要转义，特别是反斜杠（\\）
        String specialCharacters = "[\'\"\\\\/,\\.\\;]";
        Pattern pattern = Pattern.compile(specialCharacters);
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    }




}